package cn.twh.wall.service;

import cn.twh.wall.config.WallConfig;
import cn.twh.wall.constant.WallErrorConstants;
import cn.twh.wall.constant.WallTemplateConstants;
import cn.twh.wall.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Service
public class JsonWallService {

    private final BeetlHandle beetlHandle;
    private final WallConfig wallConfig;

    @Autowired
    public JsonWallService(BeetlHandle beetlHandle, WallConfig wallConfig) {
        this.beetlHandle = beetlHandle;
        this.wallConfig = wallConfig;
    }

    /**
     * 普通报文挡板逻辑
     *
     * @param request 请求体
     * @param headers http请求头
     * @param api     api名称
     * @return 响应报文
     * @throws IllegalArgumentException 当properties配置不合法时抛出改异常
     */
    public String dpHandler(JSONObject request, Map<String, String> headers, String api) throws IllegalArgumentException {
        JSONObject reqJson = JSONObject.parseObject(JSONObject.toJSONString(request));
        if (reqJson == null) {
            reqJson = new JSONObject();
        }
        reqJson.put("request_headers", headers);
        reqJson.put("request_api", api);
        // 判断是否存在超时、失败标识数据，如存在则返回超时模板
        if (wallConfig.containsFailedFlag(reqJson, api)) {
            return beetlHandle.genTemplateTargetString(WallTemplateConstants.TEMPLATE_FAILED, reqJson);
        }
        if (wallConfig.containsTimeOutFlag(reqJson, api)) {
            return beetlHandle.genTemplateTargetString(WallTemplateConstants.TEMPLATE_TIMEOUT, reqJson);
        }
        // 获取各种情况比率，作为权重
        int failRate = wallConfig.getFailedRate(api);
        int timeOutRate = wallConfig.getTimeOutRate(api);
        int successRate = 100 - failRate - timeOutRate;
        if (successRate < 0) {
            throw new IllegalArgumentException(WallErrorConstants.RATE_CONFIG_ERROR);
        }
        String[] template = new String[]{WallTemplateConstants.TEMPLATE_SUCCESS, WallTemplateConstants.TEMPLATE_FAILED, WallTemplateConstants.TEMPLATE_TIMEOUT};
        int index = RandomUtil.weightIndex(successRate, failRate, timeOutRate);
        // 通过beetl 模板构建 响应
        return beetlHandle.genTemplateTargetString(template[index], reqJson);
    }

    /**
     * 文件上传挡板服务
     *
     * @param headers  html接入请求头
     * @param filename 文件名
     * @return 响应报文
     */
    public String dpHandler(MultiValueMap<String, String> headers, String filename) {
        // TODO Auto-generated method stub
        return null;
    }
}
